//
//  WBMainViewController.swift
//  传智微博
//
//  Created by FYXJ（6） on 2018/8/27.
//  Copyright © 2018年 FYXJ（6）. All rights reserved.
//

import UIKit

/// 主控制器
class WBMainViewController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()

        setupChildController()
        setupComposeButton()
    }
    
    //设置设备方向支持
    
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .portrait
    }
    /// 撰写微博
    //    FIXME: 没有实现
    @objc private func composeStatus() {
       print("撰写微博")
        let VC = UIViewController()
        
        VC.view.backgroundColor = UIColor.cz_random()
        
        let na = UINavigationController(rootViewController: VC)
        VC.navigationItem.leftBarButtonItem  = UIBarButtonItem(title: "返回", target: self, action: #selector(backAction))
        
        let animation = CATransition()
        animation.duration = 0.35
        animation.timingFunction = CAMediaTimingFunction.init(name: "default")  //UIViewAnimationCurve.easeInOut
//        CAMediaTimingFunction
        animation.type = kCATransitionPush
        animation.subtype = kCATransitionFromRight

        view.window?.layer.add(animation, forKey: nil)
        present(na, animated: false, completion: nil)
//        　 CATransition *animation = [CATransition animation];
//
//        animation.duration = 0.35;
//
//        animation.timingFunction = UIViewAnimationCurveEaseInOut;
//
//        animation.type = kCATransitionPush;
//
//        　 　 animation.subtype = kCATransitionFromRight;
//
//        [self.view.window.layer addAnimation:animation forKey:nil];
//
//        [self presentViewController:setVC animated:NOcompletion:nil];
//        present(na, animated: true, completion: nil)
    }
    
    @objc private func backAction()
    {
//        dismiss(animated: true, completion: nil)
        
        let animation = CATransition()
        animation.duration = 0.5
        animation.timingFunction = CAMediaTimingFunction.init(name: "default")
        animation.type = kCATransitionPush;
        animation.subtype = kCATransitionFromLeft;
        view.window?.layer.add(animation, forKey: nil)
        dismiss(animated: false, completion: nil)
//        CATransition *animation = [CATransition animation];
//
//        　　animation.duration = 0.35;
//
//        　　animation.timingFunction = UIViewAnimationCurveEaseInOut;
//
//        　　animation.type = kCATransitionPush;
//
//        　　animation.subtype = kCATransitionFromLeft;
//
//        　　　　　　[self.view.window.layer addAnimation:animation forKey:nil];
//
//        　   　   [selfdismissViewControllerAnimated:NOcompletion:nil];
    }
    private lazy var composeBtn: UIButton = UIButton.cz_imageButton("tabbar_compose_icon_add", backgroundImageName: "tabbar_compose_button")
}

//    extension 类似于OC的分类 在Swift中还可以用来切分代码块
//可以把相近功能的函数 放在一个extension
//便于代码维护
//注意：和OC一样 在extension中不能定义属性 只能定义方法
// MARK :- 设置界面
extension WBMainViewController {
   
   /// 设置所有子控制器
    
    private func setupComposeButton() {
        tabBar.addSubview(composeBtn)
        
//        计算按钮的宽度、、
        let count = CGFloat(childViewControllers.count)
        let w = tabBar.bounds.width/count - 1
        
        composeBtn.frame = tabBar.bounds.insetBy(dx: 2*w, dy: 0)
        
        composeBtn.addTarget(self, action:#selector(composeStatus), for: .touchUpInside)
    }
   private func setupChildController() -> () {
    
    guard let path = Bundle.main.path(forResource: "main.json", ofType: nil),
        let data = NSData(contentsOfFile: path),
        let array = try? JSONSerialization.jsonObject(with: data as Data, options: []) as? [[String : AnyObject]]
        else {
        return
    }
  
    var arrayM = [UIViewController]()
    for dict in array!
    {
        arrayM.append(controller(dict: dict))
    }
    viewControllers = arrayM
    }
  
    
    
    
    /// 使用字典创建一个子控制器
    ///
    /// - Parameter dict: 信息字典（clsname，title，imageName）
    /// - Returns: 子控制器
    private func controller(dict:[String:AnyObject]) -> UIViewController {
       
        //取得字典内容
        guard let clsName = dict["clsName"] as? String,
            let title = dict["title"] as? String,
            let imageName = dict["imageName"] as? String,
            let cls = NSClassFromString(Bundle.main.namespace + "." + clsName) as? WBBaseViewController.Type,
            let visitorInfo = dict["visitorInfo"] as? [String: String]
            else {
                
            return UIViewController()
        }
        //创建控制器
        //1> 将clsName 转换成 cls
        
        let vc = cls.init()
        vc.visitorInfoDic = visitorInfo
        vc.title = title
        vc.tabBarItem.image = UIImage(named: "tabbar_" + imageName)
        vc.tabBarItem.selectedImage = UIImage(named: "tabbar_" + imageName + "_highlighted")?.withRenderingMode(.alwaysOriginal)
        vc.tabBarItem.setTitleTextAttributes([NSAttributedStringKey.foregroundColor: UIColor.orange], for: .highlighted);

    
       vc.tabBarItem.setTitleTextAttributes([NSAttributedStringKey.font:UIFont.systemFont(ofSize: 10)], for: UIControlState.normal)
        let Nav = WBNavigationController(rootViewController: vc)
        return Nav
    }
}
